package org.six11.ss.client;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import org.jdom.Element;
import org.six11.ss.shared.Message;
import org.six11.util.adt.MultiState;

/**
 * 
 *
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class ScoresMessageHandler extends AWTMessageHandler {

  /**
   * @param state
   */
  public ScoresMessageHandler(MultiState state) {
    super(state);
  }

  /**
   * 
   */
  @Override
  public void handleAWT(Message msg) {
    bug("received message:\n" + msg.toXml());
    SortedSet<ScoreInfo> scores = new TreeSet<ScoreInfo>(ScoreInfo.nameComparator);
    List scoreObjects = msg.getRoot().getChildren("score");
    for (Object scoreObj : scoreObjects) {
      Element scoreElm = (Element) scoreObj;
      ScoreInfo scoreInfo = new ScoreInfo();
      scoreInfo.setPlayerName(scoreElm.getAttributeValue("playerNick"));
      if (scoreElm.getAttribute("lifetimeScore") != null) {
        scoreInfo.setLifetimeScore(Integer.parseInt(scoreElm.getAttributeValue("lifetimeScore")));
      }
      if (scoreElm.getAttribute("gameScore") != null) {
        scoreInfo.setGameScore(Integer.parseInt(scoreElm.getAttributeValue("gameScore")));
      }
      if (scoreElm.getAttribute("roundScore") != null) {
        scoreInfo.setRoundScore(Integer.parseInt(scoreElm.getAttributeValue("roundScore")));
      }
      // bug(scoreInfo.toString());
      scores.add(scoreInfo);
    }
    state.setValue(ClientStateNames.K_SCORES, scores);
  }

}
